package com.wisemoresystem.seal.util.json;

import com.wisemoresystem.seal.config.Config;
import com.wisemoresystem.seal.util.des.DESCoder;
import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSON;

/**
 * json <---> cookie 互相转换
 * 
 * @author uninf
 * 
 */
public class JsonCookieTools {

	private static byte[] key;

	static {
		key = Base64.decodeBase64(Config.SESSION_KEY);
	}

	/**
	 * 对象->Json,加密字符串
	 * 
	 * @param name
	 * @param obj
	 * @return
	 */
	public static String objToJiaMiJson(Object obj) {
		if (obj == null) {
			return null;
		}

		String jsonStr = JSON.toJSONString(obj);

		// 加密
		byte[] data = null;
		try {
			data = DESCoder.encrypt(jsonStr.getBytes(), key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		jsonStr = Base64.encodeBase64String(data);

		return jsonStr;
	}// #objToJson

	/**
	 * json->Object 解密字符串
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static Object jsonToObj(String jsonStr, Class<?> clazz) {
		// 解密
		byte[] data = Base64.decodeBase64(jsonStr);
		try {
			data = DESCoder.decrypt(data, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		jsonStr = new String(data);

		// 求值

		Object obj = JsonTools.jsonStrToJsonObject(jsonStr, clazz);

		return obj;
	}// jsonToObj

}
